<?php
namespace app\common\service;

use think\facade\Request;
use think\Db;
use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Util\ResponseChecker;
use Alipay\EasySDK\Kernel\Config;
 
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2022/7/13
 * Time: 17:29
 */
class AlipayService
{
	
	
	//支付
    public static function pay($order_id,$order_type=1,$user_id,$source){
        if (!$order_id) {
			return ['code'=>'0','msg'=>'确少订单id']; 
        }
		/*
		if($order_type == 1){//订单
			$order_info = Db::name('course_order')->where('id',$order_id)->find();
			$title = '购买课程';
		}elseif($order_type == 2){//订单
			$order_info = Db::name('course_order')->where('id',$order_id)->find();
			$title = '购买服务';
		}else{
			return ['code'=>'0','msg'=>'订单类型错误']; 
		}*/
		$order_info = Db::name('course_order')->where('id',$order_id)->find();
		$order_type = $order_info['type'];
		if($order_type == 1){//订单
			$title = '购买课程';
		}elseif($order_type == 2){//订单
			$title = '购买服务';
		}else{
			return ['code'=>'0','msg'=>'订单类型错误']; 
		}
		
		if($order_info['status'] != 1){
			$arr = array('code' => 0, 'msg' => '订单不是待支付状态');
			return $arr;
			exit();
		}
		if ($order_info['user_id'] != $user_id) {
			$arr = array('code' => 0, 'msg' => '不能支付其他人的订单');
			return $arr;
			exit();
		}
		$user_id = $order_info['user_id'];
		$price = $order_info['order_money'];
		if($order_info['is_pay'] == 1){
			$arr = array('code' => 0, 'msg' => '已经支付过了');
			return $arr;
			exit();
		}
		
					
		//1. 设置参数（全局只需设置一次）
		Factory::setOptions(self::getOptions());
		 
		try {
		    if($source == 1){
		        //app支付
		        $result = Factory::payment()->App()->pay($title,$order_info['order_sn'],$price);
		    }elseif($source == 2){
		        $returnUrl =  config('web_host').'/#/platforms/web/my/order';
		        //pc支付
			    $result = Factory::payment()->Page()->pay($title,$order_info['order_sn'],$price,$returnUrl);
		    }else{
		        $returnUrl =  config('web_host').'/#/platforms/web/my/order';
		        //h5支付
			    $result = Factory::payment()->Wap()->pay($title,$order_info['order_sn'],$price,$returnUrl,$returnUrl);
		    }
			
			
			$responseChecker = new ResponseChecker();
			//3. 处理响应或异常
			if ($responseChecker->success($result)) {
				//echo "调用成功". PHP_EOL;
				return ['code'=>'1','msg'=>'success','data'=>$result->body]; 
			} else {
				return ['code'=>'0','msg'=>$result->msg."，".$result->subMsg];
			}
		} catch (Exception $e) {
			return ['code'=>'0','msg'=>$e->getMessage()];
		}    
    }
    
	
	public static function getOptions()
	{
		$options = new Config();
		$options->protocol = 'https';
		//$options->gatewayHost = 'openapi.alipaydev.com';
		$options->gatewayHost = 'openapi.alipay.com';
		$options->signType = 'RSA2';
	 
		$options->appId = '2021005151606716';
	 
		// 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
		$options->merchantPrivateKey = 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCA1Zg8iKvVI+TyYKA4cAd0lPKe6wWvev5DnPC/xAfouoQkZj9FPzWzqJ9HXWa85d0QJFxHNXSDh6ye+knMB/zcHPkCOnEkOdYfsPgHFlj+XKbHBe0pNccSrItBQZvlJlmpDypTcVgkNgwnuCvIMoJaYFQMCZ+Y8AVEjMLbg69fC5LVUQSwWR1746e+PZOe7SiLsSFJ1wEM/VVyfP+d3D3yT63MqVW3CmW0+w00x2ED0bvgaND9JCTdK4/yMM9zwvUJkaEvj0e4WEXWhey4UnmU8rXqXZkMhchGQs0LNjeV6F/EYhvXwELviRwdR9cJoPcPF3bEaxywBvQEJH2KiUPLAgMBAAECggEANb/nKaojdmLpS63AaotisOLLbj3DO3jmx7KcRoU0f4YBR2ZZEzzR3MiG2zE+gaSs2+Uvko3ctFtQS2tEipjyh6qWwLU9Ks3uZX5hnCNYsZZaBkKUtVK4YTQXTPxgW/PqCDxJflKVYVYjMBcIPRfFhosVxYfmS9oneHf5e7eu3MnRxutOmauoJBOvT108uJ8odQKCp3eFtQBPJMqC6O+uyTQ9RmdZU7Vl0gX29yM8UykGXzl5Kno2RWpCEQecu4J0NGEdIa0pjUJTpc0jZAWe/UFz85YmbjS3mRcLRy3ZqxuFO24cPbfJWc2ZD92vGNUTxmh0pyg76514MFxi1/YTYQKBgQC3rhFT2WulF87h92ssnqcVTghihrFwH4tZcvXiC41TryRWqRUwuuMhW49o9mhWcmvugzPwJqeP32A8bq7a1edWjmL/MA2ae5MIFzpqCBSjaE7xvanV2UZF1VaC8pGh9hilW9K9pOBxUJ2Fvpcjx8GvH7feVmoFbtXjKBc/Clln0wKBgQCzj2QxGhg0Sa3vtmm5eH6Kv0UW+seDqi6gXNdu4kyYf1NaVcbRpTi5TBIt57mpClp/CCfSoBzi5OJOvsvjGPf9xNF6B6ZGKrOEpE3D4XZN17IK8sOCviUlPqgy98TEIU7HgfCJ//o2UCaaWEKjzcCHEH9E/cW9IQH9uTKcCF7xKQKBgBdQyjRJkgd32TQH0xvr26uxpxDSpi1kY6zsEdgqvTrVLZiuh9kSsAgo9jBNrvriNV8mWm5uibCSm0WwixOOOXpcQqa/88obS5OoVyrkcbI4aGT5PVi+5tOwe/XNUr0rXv+Gg169UhwwLn6urcLF9YkETrOzZmvgINhf22uOJcEvAoGAHSE+F9kr5A+v8Bufuz8ZCFlPVBMLGwkY11s4d/yugG7njtgrkQdE1IrKyDe3nvzXAZTJIRpolUackDnTydvbH4g2k516FBgJV5NwKj8Bek9ryurnXOaMECbCEsKvYUImDae+5iRo6zbFjHSVGw3eFgtPGloxIiWgtRC+bSHOhUECgYEAkpA4tKIpQMc/yxq0c9iTD4euKHXhjO8/WCt7raxBgpAbe+REkED/hqlwGHfX0mv18vQplGVQ+aL4ClpMjLIWYcfi3StM322EJ2kcPdNTu8cLvPvLadlF/JSJo5g0f9yb81aqZc3Zsh6DmKI9ZScxU3Gn3RkN7Y6XrMPVzeDmTuI=';
	 
		//$options->alipayCertPath = '<-- 请填写您的支付宝公钥证书文件路径，例如：/foo/alipayCertPublicKey_RSA2.crt -->';
		//$options->alipayRootCertPath = '<-- 请填写您的支付宝根证书文件路径，例如：/foo/alipayRootCert.crt" -->';
		//$options->merchantCertPath = '<-- 请填写您的应用公钥证书文件路径，例如：/foo/appCertPublicKey_2019051064521003.crt -->';//注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
		
		$options->alipayPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkl7B53YyqVMVBx8J6JUU5nsONMxSJ1ZhRrd0Zsw8RVviAjLjsFsiH7dSt7OhNKy3AecNciXI6TK1vPJwQKov9mNPQt9L+NT72GkmIWzpaT5bkXtsQeqKIzUenbjGw2TmRsTNJaq5i83/rLfRi+k6ZQNVJvMQ8jzasneptOmSREsy0X99tKAROKrcmOlwHfdudanhxQYXL1FMaMZQ3KvgzvMr2a/jU/zaag94K4VBRUU9GsRaL2o1fk23xdbMEOVABcF6KqWuWoQP1fYEDHDNV5dxUvWuBwGptbWdhhLprUObsNE3c6ttCRjSMHby2/Da0qg0F0PI86tAcPjSZySx7wIDAQAB';
	 
		//可设置异步通知接收服务地址（可选）
		$options->notifyUrl = config('app_host').'/api/login/alnotify';
	 
		return $options;
	}

}